package pattern.controller;

import cn.hutool.core.convert.Convert;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import pattern.WorkServiceTool;
import pattern.gen.dto.GenTable;
import pattern.gen.dto.GenTableColumn;
import pattern.gen.model.TableDataInfo;
import pattern.result.ResponseData;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController
{

    TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }
    /**
     * 查询代码生成列表
     */
    @GetMapping("/list")
    public TableDataInfo genList(GenTable genTable)
    {
        List<GenTable> list = WorkServiceTool.getGenTableService().selectGenTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{tableId}")
    public ResponseData<?> getInfo(@PathVariable Long tableId)
    {
        GenTable table = WorkServiceTool.getGenTableService().selectGenTableById(tableId);
        List<GenTable> tables = WorkServiceTool.getGenTableService().selectGenTableAll();
        List<GenTableColumn> list = WorkServiceTool.getGenTableColumnService().selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return new ResponseData<>(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    public TableDataInfo dataList(GenTable genTable)
    {
        List<GenTable> list = WorkServiceTool.getGenTableService().selectDbTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{tableId}")
    public TableDataInfo columnList(Long tableId)
    {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = WorkServiceTool.getGenTableColumnService().selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */
    @PostMapping("/importTable")
    public ResponseData<?> importTableSave(String tables,String tableSchema)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = WorkServiceTool.getGenTableService().selectDbTableListByNames(tableNames,tableSchema);
        WorkServiceTool.getGenTableService().importGenTable(tableList);
        return new ResponseData<>(true);
    }

    /**
     * 删除代码生成
     */
    @DeleteMapping("/{tableIds}")
    public ResponseData<?> remove(@PathVariable Long[] tableIds)
    {
        WorkServiceTool.getGenTableService().deleteGenTableByIds(tableIds);
        return new ResponseData<>(true);
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableId}")
    public ResponseData<?> preview(@PathVariable("tableId") Long tableId) throws IOException
    {
        Map<String, String> dataMap = WorkServiceTool.getGenTableService().previewCode(tableId);
        return new ResponseData<>(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        byte[] data = WorkServiceTool.getGenTableService().downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = WorkServiceTool.getGenTableService().downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        /*response.addHeader("Access-Control-Allow-Origin", "*");*/
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"pattern.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}